# -*- coding: utf-8 -*-

import os
import sys
from contextlib import closing
import math, pytz
import jinja2
import hashlib
import time
import werkzeug.utils
import datetime
import openerp
from openerp.fields import Datetime
import simplejson
from openerp import http
from openerp.http import request
from openerp.addons.wechat.enterprise import WxApi, WxApplication, WxTextResponse, WxNewsResponse, WxArticle, WxLink
from openerp.addons.website_mshop.pools import ModelPool, CursorProxy, common_functions, PageProxy, _slug
ISODATEFORMAT = '%Y-%m-%d'
ISODATETIMEFORMAT = "%Y-%m-%d %H:%M:%S"
UTCDATETIMEFORMAT = "%Y-%m-%dT%H:%M:%SZ"
SUPERUSER_ID = 1

if hasattr(sys, 'frozen'):
    # When running on compiled windows binary, we don't have access to package loader.
    path = os.path.realpath(os.path.join(os.path.dirname(__file__), '..', 'html'))
    loader = jinja2.FileSystemLoader(path)
else:
    loader = jinja2.PackageLoader('openerp.addons.dftg_weixin', "html")

env = jinja2.Environment('<%', '%>', '${', '}', '%', loader=loader, autoescape=True)

class ControllerWeiXinPack(http.Controller):
    weixin_app = None

    def __init__(self):
        env.globals['_pool'] = ModelPool()
        env.globals['_cr'] = CursorProxy()
        env.globals['_page'] = PageProxy()
        env.globals['_slug'] = _slug
        env.globals.update(common_functions)
        env.filters['tojson'] = simplejson.dumps

    # 提货记录form页面
    @http.route('/wx/product/package/<int:package_id>', auth='weixin')
    def show_product_package(self, package_id,  **kw):
        cr, context, pool = request.cr, request.context, request.registry
        uid = request.session.uid
        users_obj = pool.get('res.users').browse(cr, uid, uid, context=context)
        package_row = pool.get('product.package').search_read(cr, uid, [('id', '=', package_id)],
                                        ['user_id', 'so_id', 'name', 'package_qty', 'start_datetime', 'is_done',
                                         'end_datetime', 'person_qty', 'is_print', 'product_name', 'note',
                                         'product_package_line'], context=context)[0]
        line_dict = pool.get('product.package.line').search_read(cr, uid, [('id', 'in', package_row.get('product_package_line'))],
                                                ['product_name', 'product_qty'], context=context)
        template = env.get_template("package/pack.html")
        package_row.update({'error': '',
                            'uid': users_obj.name,
                            'user_id': package_row.get('user_id', False) and package_row.get('user_id')[1] or '',
                            'so_id': package_row.get('so_id') and package_row.get('so_id')[1],
                            'product_package_line': line_dict
                            })
        return template.render({
            'package_row': package_row
        })

    def handling_http_return_val(self, val_type, val, context=None):
        try:
            if val_type == 'datetime':
                return_val = val
            elif val_type == 'int':
                return_val = int(val)
            else:
                return_val = val
        except Exception as e:
            return_val = val
        return return_val

    @http.route('/wx/product/package/write', type='json', auth='weixin')
    def product_package_write(self, **kw):
        try:
            cr, context, pool = request.cr, request.context, request.registry
            uid = request.session.uid
            package_obj = pool.get('product.package')
            field_type = {'start_datetime': 'datetime',
                          'end_datetime': 'datetime',
                          'person_qty': 'int',
                          'id': 'int'}
            vals = {key: self.handling_http_return_val(field_type.get(key), val, context=context) for key, val in request.jsonrequest.iteritems()
                    if key in ['start_datetime', 'end_datetime', 'person_qty', 'id'] and val}
            package_id, return_val = vals.get('id'), {}
            del vals['id']
            user_dict = pool.get('res.users').search_read(cr, uid, [('id', '=', uid)], ['name'], context=context)[0]
            if not package_obj.search(cr, uid, [('id', '=', package_id), ('user_id', '=', uid)], context=context):
                vals.update({'user_id': uid})
            if vals:
                package_obj.write(cr, uid, package_id, vals, context=context)
                return_val.update(vals)
            return_val.update({'user_id': user_dict.get('name')})
            return return_val
        except Exception as e:
            if hasattr(e, 'message'):
                return {'message': '' % e.message}
            else:
                return {'message': u'写入错误，请联系管理员！'}

    @http.route('/wx/product/package/done', type='json', auth='weixin')
    def product_package_done(self, **kw):
        try:
            cr, context, pool = request.cr, request.context, request.registry
            uid = request.session.uid
            package_obj = pool.get('product.package')
            package_obj.write(cr, uid, request.jsonrequest.get('id'), {'is_done': True}, context=context)
            return {'is_done': True}
        except Exception as e:
            if hasattr(e, 'message'):
                return {'message': '%s' % e.message}
            else:
                return {'message': u'写入错误，请联系管理员！'}



